package com.yn.xgame.access;

import com.google.protobuf.InvalidProtocolBufferException;
import com.yn.xgame.*;
import com.yn.xgame.message.C2APbMessage;
import com.yn.xgame.pb.ClientAccessProto;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * AccessApp
 * Created by wangboo on 2017/7/12.
 */
public class AccessApp implements NettyProtobufHandler.Callback {

    private static final Logger logger = LoggerFactory.getLogger(AccessApp.class);
    public static final ZkClient client = new ZkClient();
    public static final AccessServer accessServer = new AccessServer();
    private static NettyServer nettyServer;
    private static LoadInfoWatcher loadInfoWatcher;

    public static void main(String[] args) throws Exception {
        AccessApp instance = new AccessApp();
        loadInfoWatcher = new LoadInfoWatcher(client, GlobalSetting.ZK_PREFIX + "/date",
                accessServer.loadInfoManager, accessServer);
        client.connect("127.0.0.1:2181", loadInfoWatcher);
        int port = 3000;
        nettyServer = new NettyServer(port, instance);
        logger.debug("AccessServer startup, bind at: {}", port);
        accessServer.startup();
        loadInfoWatcher.doWatch();
        nettyServer.start();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, byte[] bin) {
        try {
            ClientAccessProto.C2AMessage msg = ClientAccessProto.C2AMessage.parseFrom(bin);
            logger.debug("access recv: {}", msg);
            accessServer.pushMessage(new C2APbMessage(ctx, msg));
        } catch (InvalidProtocolBufferException e) {
            logger.error("parse C2AMessage failed: {}", bin);
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) {
    }
}
